<?php
declare (strict_types=1);

namespace app\service;

use League\OAuth2\Client\Provider\GenericProvider;
use League\OAuth2\Client\Token\AccessToken;

class QService{

    // 配置提供商
    private $provider;
    private $clientId;//从配置读取APP ID
    private $clientSecret;// APP Key
    private $redirectUri;//与QQ互联一致

    public function __construct()
    {
//        $this->apikey = env('AI.ALIAPIKey');
//        if(empty($this->apikey)){
//            throw new \Exception("密钥不存在");
//        }
        $this->clientId = env('QQ_APPID');
        $this->clientSecret = env('QQ_APPKEY');
        $this->redirectUri = 'http://www.okshiwen.cn/';
        $this->provider = new GenericProvider([
            'clientId'     => $this->clientId,     // 从配置读取APP ID
            'clientSecret' => $this->clientSecret,    // APP Key
            'redirectUri'  => $this->redirectUri, // 与QQ互联一致
            'urlAuthorize' => 'https://graph.qq.com/oauth2.0/authorize',
            'urlAccessToken' => 'https://graph.qq.com/oauth2.0/token',
            'urlResourceOwnerDetails' => 'https://graph.qq.com/oauth2.0/me'
        ]);
    }

    /**
     * @return GenericProvider
     */
    public function qqLogin()
    {
        $authUrl = $this->provider->getAuthorizationUrl();
        session('oauth_state', $this->provider->getState());
        return $authUrl;
    }

    //回调
    public function callback($code){
        $clientId = $this->clientId;
        $clientSecret = $this->clientSecret;
        $redirectUri = $this->redirectUri;

        $url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code".
            "&client_id={$clientId}&client_secret={$clientSecret}".
            "&code={$code}&redirect_uri={$redirectUri}";

        $response = file_get_contents($url);
        parse_str($response, $tokenData);

        $accessToken = $tokenData['access_token'] ?? null;

        // 获取OpenID
        $openidUrl = "https://graph.qq.com/oauth2.0/me?access_token={$accessToken}";
        $response = file_get_contents($openidUrl);

        $openid = '';
        if (preg_match('/callback\(\s*(\{.*?\})\s*\)/i', $response, $matches)) {
            $openidData = json_decode($matches[1], true);
            $openid = $openidData['openid'] ?? null;

            if (!$openid) {
                throw new Exception('获取openid失败');
            }

        } else {
            throw new Exception('无效的openid响应格式');
        }

        $userInfo = $this->getQQUserInfo($accessToken, $openid);
        // 处理用户登录/注册逻辑
        // 例如：查询数据库，如果用户不存在则创建，否则登录
        // ...
        $info = [
            'openid'=> $openid,
            'userInfo'=> $userInfo,
        ];
        return $info;
    }

    public function getQQUserInfo($accessToken, $openid){
        $url = "https://graph.qq.com/user/get_user_info?" . http_build_query([
                'access_token' => $accessToken,
                'oauth_consumer_key' => $this->clientId,
                'openid' => $openid
            ]);

        $response = file_get_contents($url);
        return json_decode($response, true);
    }

}